package cn.ray.springframework.beans.factory.support;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.ray.springframework.beans.BeansException;
import cn.ray.springframework.beans.PropertyValue;
import cn.ray.springframework.beans.PropertyValues;
import cn.ray.springframework.beans.factory.*;
import cn.ray.springframework.beans.factory.config.AutowireCapableBeanFactory;
import cn.ray.springframework.beans.factory.config.BeanDefinition;
import cn.ray.springframework.beans.factory.config.BeanPostProcessor;
import cn.ray.springframework.beans.factory.config.BeanReference;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

//实例化Bean类
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {

    private InstantiationStrategy instantiationStrategy = new SimpleInstantiateStrategy();

    //在创建Bean时完成前置和后置的处理
    @Override
    protected Object createBean(String name, BeanDefinition beanDefinition, Object[] args) throws BeansException {
        Object bean = null;
        try {
            //对bean对象的实例化操作
            bean = createBeanInstance(beanDefinition, name, args);

            //实例化对象后，做对象的属性填充工作
            applyPropertyValues(name, bean, beanDefinition);

            //执行bean的初始化方法，以及前置后置处理方法
            bean = initializeBean(name, bean, beanDefinition);
        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed", e);
        }
        registerDisposableBeanIfNecessary(name, bean, beanDefinition);

        if (beanDefinition.isSingleton()) {
            //放到单例对象缓存（hashmap）
            addSingleton(name, bean);
        }

        return bean;
    }

    private void registerDisposableBeanIfNecessary(String name, Object bean, BeanDefinition beanDefinition) {

        //非Singleton类不执行销毁方法，Bean生命周期不由Spring管理
        if (!beanDefinition.isSingleton()) return;


        if (bean instanceof DisposableBean || StrUtil.isNotEmpty(beanDefinition.getDestroyMethodName())) {
            registerDisposableBean(name, new DisposableBeanAdapter(bean, name, beanDefinition));
        }
    }

    private Object initializeBean(String name, Object bean, BeanDefinition beanDefinition) {

        if (bean instanceof Aware) {
            if (bean instanceof BeanFactoryAware) {
                ((BeanFactoryAware) bean).setBeanFactory(this);
            }
            if (bean instanceof BeanNameAware) {
                ((BeanNameAware) bean).setBeanName(name);
            }
            if (bean instanceof BeanClassLoaderAware) {
                ((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
            }
        }

        Object wrappedBean = applyBeanPostProcessorsBeforeInitialization(bean, name);

        //TODO:invokeInitBean--待完成

        try {
            invokeInitMethods(name, wrappedBean, beanDefinition);
        } catch (Exception e) {
            throw new BeansException("invocation of init method of bean[" + name + "]failed");
        }

        wrappedBean = applyBeanPostProcessorsAfterInitialization(bean, name);
        return wrappedBean;
    }

    //实验7主要完成这里，调用init方法
    private void invokeInitMethods(String name, Object bean, BeanDefinition beanDefinition) throws Exception {
        //方式1：实现了InitializingBean 直接调用after..函数
        if (bean instanceof InitializingBean) {
            ((InitializingBean) bean).afterPropertiesSet();
        }

        //方式2：xml配置文件中声明init方法 反射获取调用
        String initMethodName = beanDefinition.getInitMethodName();
        if (StrUtil.isNotEmpty(initMethodName)) {
            //反射获取方法
            Method initMethod = beanDefinition.getBeanClass().getMethod(initMethodName);
            if (initMethod == null) {
                throw new BeansException("could not find a method named" + initMethodName);
            }
            //调用bean对象的方法 invoke(Object obj,Object...args) 分别为目标对象和参数列表
            initMethod.invoke(bean);
        }
    }

    //用于确定要使用那个构造函数，通过参数匹配来选择合适的对象
    protected Object createBeanInstance(BeanDefinition beanDefinition, String beanName, Object[] args) {
        Constructor constructorToUse = null;
        Class<?> beanClass = beanDefinition.getBeanClass();
        //获取UserService类的所有构造函数
        Constructor<?>[] declaredConstructors = beanClass.getDeclaredConstructors();

        for (Constructor ctor : declaredConstructors) {
            //找到一个参数长度匹配的构造函数
            if (args != null && ctor.getParameterTypes().length == args.length) {
                constructorToUse = ctor;
                break;
            }
        }

        //调用strategy使用反射api创建对象实例，并返回创建的对象
        return getInstantiationStrategy().instantiate(beanDefinition, beanName, constructorToUse, args);
    }

    //做bean的属性填充
    private void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
        PropertyValues propertyValues = beanDefinition.getPropertyValues();
        for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
            String name = propertyValue.getName();
            Object value = propertyValue.getValue();

            if (value instanceof BeanReference) {//如果属性值是对另一个Bean的引用
                //a依赖b，获取b对象的实例化
                BeanReference beanReference = (BeanReference) value;
                value = getBean(beanReference.getBeanName());
            }

            // 属性填充
            BeanUtil.setFieldValue(bean, name, value);
        }
    }

    public InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }

    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
        this.instantiationStrategy = instantiationStrategy;
    }

    //允许处理器对Bean进行修改
    @Override
    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException {
        //接受已经存在的Bean对象
        Object result = existingBean;
        //遍历所有的前置处理器
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            //调用每个处理器的post方法处理bean
            //返回null，中断处理链
            Object current = processor.postProcessBeforeInitialization(result, beanName);
            if (current == null) return result;
            //否则更新bean，继续传入处理链
            result = current;
        }
        return result;
    }

    @Override
    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessAfterInitialization(result, beanName);
            if (current == null) return result;
            result = current;
        }
        return result;
    }
}
